<template>
  <div class="student-container">
    <el-row :gutter="5">
      <el-col :span="4">
        <el-input placeholder="输入姓名关键字" v-model="studentSearch.sname"/>
      </el-col>
      <el-col :span="4">
        <el-input placeholder="输入住址关键字" v-model="studentSearch.addr"/>
      </el-col>
      <el-col :span="4">
        <el-select v-model="studentSearch.cid" placeholder="请选择所在班级" style="width: 100%">
          <el-option label="所有班级" value="0"></el-option>
          <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button type="success" icon="el-icon-plus" @click="handleEdit">添加</el-button>
      </el-col>

    </el-row>

    <el-card class="box-card">
      <el-table
        :data="students"
        style="width: 100%">
        <!--<el-table-column-->
        <!--  label="学号"-->
        <!--  prop="sid"-->
        <!--  width="180">-->
        <!--</el-table-column>-->
        <el-table-column
          label="图像"
          align="center"
          width="180">
          <template slot-scope="scope">
            <img :src="scope.row.photo" width="100" height="50">
          </template>
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="sname"
          width="180">
        </el-table-column>
        <el-table-column
          label="性别"
          prop="sex"
          width="130">
        </el-table-column>
        <el-table-column
          label="年龄"
          prop="age"
          width="130">
        </el-table-column>
        <el-table-column
          label="住址"
          prop="addr"
          width="180">
        </el-table-column>
        <el-table-column
          label="所在班级"
          prop="cname"
          width="180">
        </el-table-column>

        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit"  @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--保存学生组件-->
      <el-dialog :title="title"
                 :visible="dialogFormVisible"
                 :close-on-click-modal="false">
        <el-form :model="studentForm" id="form1" ref="studentFormRef" >
          <el-form-item label="学生姓名" :label-width="formLabelWidth" >
            <el-input v-model="studentForm.sname" autocomplete="off"/>
            <div style="float: right;margin-right: 10px;z-index:100;color:red">{{errorMsg.sname}}</div>
          </el-form-item>
          <el-form-item label="学生性别" :label-width="formLabelWidth" >
            <el-select v-model="studentForm.sex" placeholder="请选择学生性别" style="width: 100%">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学生年龄" :label-width="formLabelWidth" >
            <el-input v-model="studentForm.age" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学生住址" :label-width="formLabelWidth">
            <el-input v-model="studentForm.addr" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="所在班级" :label-width="formLabelWidth" >
            <el-select v-model="studentForm.cid" placeholder="请选择所在班级" style="width: 100%">
              <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学生图像" :label-width="formLabelWidth">
            <!--文件上传组件-->
            <!--:http-request="uploadFile" 此代码代表自定义文件上传-->
            <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :file-list="fileList"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :http-request="uploadFile"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>
      <!--分页导航-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
  //1.导入学生访问的api
  import {findAll,search,edit,del,uploadFile} from "@/api/student";
  import {findClasses} from "@/api/classes";
  export default {

        name: "index",
        data(){
          return {
            students:[],      //所有的学生
            keywords:'',
            page:1,           //当前页
            pageSize:5,        //每页大小
            total:100,           //总记录数
            title:'添加学生',
            dialogFormVisible:false, //是否显示对话框
            studentForm:{},
            formLabelWidth:'120px',
            classes:{},
            studentSearch:{},        //代表搜索的学生对象
            fileList:[],             //上传文件列表
            imageUrl:'',
            errorMsg:{},             //错误信息

          }
        },
        created() {
          //this.findAll();
          this.handleCurrentChange()
          this.findClasses();
        },
        methods:{
          //1.查询所有学生
           findAll(){
              findAll().then(({data})=>{
                this.students = data.list;
                //console.log(data);
              })
          },
          //2.删除学生
           handleDelete(row){
            this.$confirm(`你真的要删除学生${row.sname}吗？`,'提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async ()=>{   //点了确定按钮后
              const data = await del(row.sid);
              console.log("del:",data);
              if(data.code === 20000){
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                  duration:1500,
                  onClose:()=>{       //此消息框结束时，刷新页面
                    this.handleCurrentChange();
                  }
                });
              }else{
                this.$message({
                  type: 'info',
                  message: `删除失败，原因是：${data.message}`
                });
              }
            })

          },
          handleRemove(file, fileList) {
            console.log(file, fileList);
          },
          handlePreview(file) {
            console.log(file);
          },
          //3.编辑学生
          handleEdit(row){
             //3.1 判断是否是修改还是添加，如果是修改就修改标题设置studentForm表单 值
             if(row.sid){
               this.title = "修改学生"
               this.studentForm = row;
               this.fileList = [];
               this.fileList.push({name:row.sname,url:row.photo});
             }else{
               this.studentForm = {};
               this.title = "添加学生";
             }
             //3.2 让对话框显示
             this.dialogFormVisible = true;
          },
          //4.搜索
          search(){
            this.handleCurrentChange(this.page);
          },
          //5.pagesize改变时触发的事件
          handleSizeChange(pageSize){
             this.pageSize = pageSize;
             console.log(`每页 ${pageSize} 条`);
             //重新发请求查询数据
            this.handleCurrentChange(this.page);
          },
          //6.当前页改变时触发的事件
          handleCurrentChange(page=1){
            this.page = page;
            console.log(`当前第 ${page} 页`);
            //向后台发送请求
            search(page,this.pageSize,this.studentSearch).then(({data})=>{
               //6.1 设置总记录数
              this.total = data.total;
              this.students = data.rows;
              console.log("data:" , data);
            })
          },
          //7.查询班级列表
          findClasses(){
             findClasses().then(({data})=>{
               this.classes = data.list;
             })
          },
          //8.保存学生
          async save(){
            //8.1 设置url地址
            let url = "/student/add";
            //8.2 判断是否是修改
            if(this.studentForm.sid){
              url = "/student/update"
            }
            //8.3 保存到数据库中
           const data =  await edit(url,this.studentForm);
             if(data.code === 20000){
               this.handleCurrentChange(this.page);
             }else{
               this.errorMsg = data.data;

               // this.$message.error({
               //   showClose:true,
               //   message:data.message,
               //   onClose:()=>{
               //
               //   }
               // })
             }

              //this.dialogFormVisible = false;       //关闭对话框
          },
          //8.4 上传文件
          uploadFile(val){
            console.log("uploadFile.....")
              //1. 定义Formdata对象
              let form = new FormData();
               console.log("val:",val)
              form.append("file",val.file);
              //2. 清空上传列表(只能一次上传一个图片)
              this.fileList = [];
              //3. 开始文件上传
              uploadFile(form,{headers: {'Content-Type': 'multipart/form-data' }})
                .then((data)=>{
                console.log("data:",data)
              if(data.code === 20000 ){
                  console.log("url",data.data.url);
                  //得到上传的图片路径
                  //this.imageUrl = data.data.url;
                  //将图片路径放到文件列表中，注意，文件格式为：{name:xxx,url:xxx}
                  this.fileList.push({name:val.raw,url:data.data.url});
                  //将图片路径赋值给学生对象的photo属性
                  this.studentForm.photo = data.data.url;
                }
             })
          },
        }
    }
</script>

<style scoped>
  .student-container{
    padding:20px;
  }
</style>
